<template>
  <div>
    <Header :left="true" leftText="返回" title="调机验收" />
    <div>
      <van-tabs v-model="active" type="card" :offset-top="80" :sticky="true" @click="tabChange" swipeable
        style="top: 8px; font-size: 15px" color="#1c6c8d">
        <!-- 未确认页面 -->
        <van-tab title="未验收" style="font-size: 15px">
          <van-row style="margin-top: 20px">
            <van-col>
              <van-image width="40" height="30" style="margin-left: -10px" src="assets/block.png" />
            </van-col>
            <van-col class="message">未验收记录
            </van-col>
          </van-row>
          <Field class="formstyle" center colon label="机台选择" placeholder="点击选择机台" @click="showPickerpShiftID1 = true"
            :value="valuepShiftName1" label-width="110px" />
          <van-popup v-model="showPickerpShiftID1" position="bottom">
            <van-picker show-toolbar :columns="searchColumns" @confirm="onConfirmpShiftID1"
              @cancel="showPickerpShiftID1 = false">
              <template #option="option">
                <div style="display: flex; flex-direction: column; align-items: center;">
                  <div>{{ option.key }}</div>
                </div>
              </template>
              <template #title>
                <Field v-model="searchKey" placeholder="请输入搜索内容" clearable />
              </template>
            </van-picker>
          </van-popup>
          <Field class="formstyle" center colon label="来源选择" placeholder="点击选择来源" @click="showPickerpShiftID2 = true"
            :value="valuepShiftName2" label-width="110px" />
          <van-popup v-model="showPickerpShiftID2" position="bottom">
            <van-picker show-toolbar :columns="columnsshift2" @confirm="onConfirmpShiftID2"
              @cancel="showPickerpShiftID2 = false">
              <template #option="option">
                <div style="display: flex; flex-direction: column; align-items: center;">
                  <div>{{ option.key }}</div>
                </div>
              </template>
            </van-picker>
          </van-popup>
          <div class="textScrol3">
            <van-checkbox-group v-model="resultnex" ref="checkboxGroup">
              <!-- 循环数据开始 -->
              <div v-for="(item, index) in itemsOne" :key="item.id">
                <div style="width: 100%; background-color: #f3f4f8; height: 5px">
                  <span></span>
                </div>
                <div class="divStyle">
                  <van-row>
                    <van-col span="2"><van-checkbox :name="index"
                        style="margin-top: 72px;margin-left: 17px;"></van-checkbox></van-col>
                    <van-col span="20" offset="1">
                      <van-row style="margin-left: 10px; margin-top: 10px">
                        <van-col span="18" style="color: #a9a9a9">设备代码:{{ item.MachineID }}</van-col>
                      </van-row>
                      <van-row style="margin-left: 10px; margin-top: 10px;color: #a9a9a9">
                        <van-col span="18">调机来源:{{ item.ResourceFrom }}</van-col>
                      </van-row>
                      <van-row style="margin-left: 10px; margin-top: 10px;color: #a9a9a9">
                        <van-col span="18">生产订单:{{ item.POrderID }}</van-col>
                      </van-row>
                      <van-row style="margin-left: 10px; margin-top: 10px;color: #a9a9a9">
                        <van-col span="20">物料号:{{ item.MaterialID }}</van-col>
                        <van-col span="4">
                          <van-button color="#138087" @click.stop="confirmmessage(item)" style="
                          width: 85px;
                          height: 40px;
                          font-size: 12px;
                          position: absolute;
                          left: 80%;
                        " type="primary" text="操作处理" />
                        </van-col>
                      </van-row>
                      <van-row style="margin-left: 10px; margin-top: 10px">
                        <van-col span="18" style="color: #a9a9a9">物料名称:{{ item.MaterialName }}</van-col>
                      </van-row>
                      <van-row style="margin-left: 10px; margin-top: 10px">
                        <van-col span="18" style="color: #a9a9a9">调机通知单描述:{{ item.NoticeMemo }}</van-col>
                      </van-row>
                      <van-row style="margin-left: 10px; margin-top: 10px">
                        <van-col span="18" style="color: #a9a9a9">生产时间: {{ item.ProDatetimeFrom }} 至 {{ item.ProDatetimeTo
                        }}</van-col>
                      </van-row>
                      <van-row style="margin-left: 10px; margin-top: 10px">
                        <van-col span="6"> </van-col>
                        <van-col span="3"> </van-col>
                        <van-col span="6"> </van-col>
                      </van-row>
                    </van-col>
                  </van-row>
                </div>
              </div>
            </van-checkbox-group>

            <van-row>
              <van-col span="10"> <van-button @click.stop="toggleAll" style="
                          width: 105px;
                          height: 40px;
                          font-size: 12px;
                          position: absolute;
                          left: 20%;
                        " type="primary" text="全选" /></van-col>
              <van-col span="10"> <van-button @click.stop="confirmmessageplus()" style="
                          width: 105px;
                          height: 40px;
                          font-size: 12px;
                          position: absolute;
                          left: 60%;
                        " type="primary" text="批量处理" /></van-col>
            </van-row>
            <!-- 循环数据结束 -->
            <!-- <van-empty v-if="itemsOne == ''" image="search" description="暂无数据" /> -->
          </div>
        </van-tab>
        <!-- 已确认页面 -->
        <van-tab title="已验收">
          <van-row style="margin-top: 20px">
            <van-col>
              <van-image width="40" height="30" style="margin-left: -10px" src="assets/block.png" />
            </van-col>
            <van-col class="message">已验收记录</van-col>
          </van-row>
          <div class="textScroll2">
            <!-- 循环数据开始 -->
            <div v-for="item2 in itemsTwo" :key="item2.id">
              <div style="width: 100%; background-color: #f3f4f8; height: 5px">
                <span></span>
              </div>
              <div class="divStyle">
                <van-row style="margin-left: 10px; margin-top: 10px">
                  <van-col span="18" style="color: #a9a9a9">设备代码:{{ item2.MachineID }}</van-col>
                </van-row>
                <van-row style="margin-left: 10px; margin-top: 10px;color: #a9a9a9">
                  <van-col span="18">调机来源:{{ item.ResourceFrom }}</van-col>
                </van-row>
                <van-row style="margin-left: 10px; margin-top: 10px">
                  <van-col span="18" style="color: #a9a9a9">生产订单:{{ Number(item2.POrderID) }}</van-col>
                </van-row>
                <van-row style="margin-left: 10px; margin-top: 10px;color: #a9a9a9">
                  <van-col span="20">物料号:{{ item2.MaterialID }}</van-col>
                  <van-col span="4">
                    <van-button color="#138087" @click.stop="confirmmessage(item2)" style="
                          width: 85px;
                          height: 40px;
                          font-size: 12px;
                          position: absolute;
                          left: 80%;
                        " type="primary" text="查看" />
                  </van-col>
                </van-row>
                <van-row style="margin-left: 10px; margin-top: 10px">
                  <van-col span="18" style="color: #a9a9a9">物料名称:{{ item2.MaterialName }}</van-col>
                </van-row>
                <van-row style="margin-left: 10px; margin-top: 10px">
                  <van-col span="18" style="color: #a9a9a9">调机通知单描述:{{ item2.NoticeMemo }}</van-col>
                </van-row>
                <van-row style="margin-left: 10px; margin-top: 10px">
                  <van-col span="18" style="color: #a9a9a9">生产时间: {{ item2.ProDatetimeFrom }} 至 {{ item2.ProDatetimeTo
                  }}</van-col>
                </van-row>
              </div>
            </div>
            <!-- 循环数据结束 -->
            <!-- <van-empty v-if="itemsTwo == ''" image="search" description="暂无数据" /> -->
          </div>
        </van-tab>
      </van-tabs>
    </div>
  </div>
</template>
<script>
import {
  CheckboxGroup,
  Popover,
  Icon,
  Button,
  CellGroup,
  Cell,
  Field,
  tab,
  tabs,
  Col,
  Picker,
  popup,
  Row,
  Image as VanImage,
  Divider,
  Checkbox,
  Pagination,
  Panel,
  Toast,
  Dialog,
  List,
  Empty
} from "vant";
import { _httpClient as _httpClientApi } from "@/libs/api";
import { _httpClient } from "@/libs/apisie";
import { storage } from "@/libs/utils";
import {
  removeToken,
  getToken,
  setBaseApiFrefix,
  getBaseApiFrefix,
} from "@/libs/auth";
import { memory } from "@/libs/utils";
Vue.use(Checkbox);
Vue.use(CheckboxGroup);
Vue.use(Empty);
Vue.use(Cell);
Vue.use(Picker);
Vue.use(popup);
Vue.use(CellGroup);
Vue.use(tab);
Vue.use(tabs);
Vue.use(Button);
Vue.use(Col);
Vue.use(Row);
Vue.use(Icon);
Vue.use(VanImage);
Vue.use(Divider);
Vue.use(Pagination);
Vue.use(Panel);
Vue.use(Dialog);
Vue.use(List);
Vue.use(Popover);
Vue.use(Toast);
import Header from "@/components/header.vue";
import apicloud from "@/libs/apicloud";
export default {
  name: "QCsecondtrial",
  components: {
    Toast,
    Popover,
    Button,
    Header,
    Icon,
    CellGroup,
    Cell,
    Field,
    tab,
    tabs,
    Col,
    Row,
    Picker,
    popup,
    Checkbox,
    CheckboxGroup
  },

  data() {
    return {
      resultnex: [],
      checked: true,
      searchColumns: [],
      searchKey: "",
      valuepShiftName1: "",
      valuepShiftName2: "APP",
      showPickerpShiftID1: false,
      showPickerpShiftID2: false,
      columnsshift1: [
      ],
      showPickerpShiftID1: false,
      columnsshift2: [
        { key: "APP", value: "APP" }, { key: "LAB", value: "LAB" }
      ],
      showPickerpShiftID2: false,
      showPopover: false,
      // 通过 actions 属性来定义菜单选项
      actions: [{ text: "延迟处理" }, { text: "填写单据" }],
      //动态加载数据
      loading: false,
      finished: false,
      allSelected: false,
      screenWidth: 0,
      checked: true,
      active: 2,
      currentPage: 1,
      user: [], //登录用户信息
      itemsOne: [],
      itemsTwo: [], //已确认明细
    };
  },
  created() {
    let oldHight = api.winWidth;
    this.screenWidth = oldHight;
    //获取当前系统登录用户
    this.user = JSON.parse(storage.get("user"));
    this.user.userId = this.user.userName;
    // alert(JSON.stringify(this.user));
    this.getUncheckedList();
    //this.queryWaitAssignList();
    //监听刷新事件
    let _this = this;
    this.$ac.addEventListener({
      name: 'reloadSecondtrial'
    }, function (ret, err) {
      _this.itemsOne = []
      _this.getUncheckedList();
    });
    this.valuepShiftName2 = this.columnsshift2[0].value;
  },
  watch: {  //实时监听搜索输入内容
    'searchKey': {
      handler(newVal) {
        let key = String(newVal);
        //alert(key);
        key = key.replace(/\s*/g, "");
        const reg = new RegExp(key, "ig");
        /* 进行筛选，将筛选后的数据放入新的数组中，‘name’键可根据需要搜索的key进行调整 */
        this.searchColumns = this.columnsshift1.filter(item => item.key.match(reg) != null);
        //alert(this.searchColumns);
      },
      deep: true,
      immediate: true,
    }
  },
  methods: {
    checkAll() {
      this.$refs.checkboxGroup.toggleAll(true);
    },
    toggleAll() {
      //this.$refs.checkboxGroup.toggleAll(true);
      this.$refs.checkboxGroup.toggleAll();
    },
    onConfirmpShiftID1(value, index) {
      this.valuepShiftName1 = this.searchColumns[index].value;
      this.showPickerpShiftID1 = false;
      this.getUncheckedListPlus(this.valuepShiftName1, this.valuepShiftName2);
    },
    onConfirmpShiftID2(value, index) {
      this.valuepShiftName2 = this.columnsshift2[index].value;
      this.showPickerpShiftID2 = false;
      this.getUncheckedListPlus(this.valuepShiftName1, this.valuepShiftName2);
    },
    onSelect(action) {
      Toast(action.text);
    },
    //已指派数据动态加载
    onLoad() {
      //页数+1
      this.loadParams.pageNum = this.loadParams.pageNum + 1;
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      setTimeout(() => {
        //this.queryCheckedAssignList();
        // 加载状态结束
        this.loading = false;

        this.finished = true;
      }, 1000);
    },
    //tab切换
    tabChange(name, title) {
      if (name == 0) {
        //查询未确认信息
        this.getUncheckedList();
      } else if (name == 1) {
        //查询已确认信息
        this.getCheckedList();
      }
    },
    //确认
    async confirmmessage(item) {
      api.openWin({
        name: "equipmentsj-QCsecondtrialItem",
        url: "./equipmentsj-QCsecondtrialItem.html",
        pageParam: {
          item: item,
          enable: this.valuepShiftName2
        },
      });
    },
    confirmmessageplus() {
      let _this = this;
      if (_this.valuepShiftName1 == "") {
        alert("请选择机台，再处理");
        return;
      }
      try {
        let searchColumnsnew = [];
        _this.resultnex.forEach(element => {
          searchColumnsnew.push(_this.itemsOne[element]);
        });
        //alert(JSON.stringify(searchColumnsnew[0]));
        searchColumnsnew.forEach(element => {
          // alert(element.Id);
          // alert(element.MachineID);
          // alert(element.POrderID);
          startRepair(element.Id, element.MachineID, element.POrderID, "", "", "");
        });
      } catch (error) {
        alert(JSON.stringify(error));
      }
    },
    //保存数据
    async startAdjust(id, machineID, orderID, recycleTest, afterAdjustStatus, result) {
      let _this = this;
      try {
        let res = await _httpClient.post(
          _httpClient.getApiPrefix() +
          "/QualityAbnormalNotice/SaveEntity",
          {
            body: {
              id: id,
              RecycleTest: recycleTest,
              AfterAdjustStatus: afterAdjustStatus,
              AdjustComfirm: _this.user.userId,
              AdjComfirmDatetime: _this.getNowTime(),
              Comfirmed: true,
              Completed: true,
              Received: true
            },
          }
        );
      } catch (e) {
        alert(JSON.stringify(e));
        Toast.fail(JSON.stringify(e));
      }
    },
    //发送消息
    async sendmessage(id, machineID, orderID, recycleTest, afterAdjustStatus, result) {
      let _this = this;

      let eventDescription = "";
      let eventDatetime = _this.getNowTime();
      let eventTypeID = "N3";
      let eventID = "";
      let messageContent = "";
      let msgContentTypeID = "";
      let pLineID = machineID;
      let pShiftID = "";
      let teamID = "";
      let pOrderID = orderID;
      let productionBarcode = "";
      let materialBarcode = "";
      let relatedEmployee = "";
      let messageStatus = "";
      let processBatchID = "";
      let beginDatetime = _this.getNowTime();
      let sendFinished = false;
      let closed = false;
      //ABN08 调机验收通过
      msgContentTypeID = "";
      eventID = "ABN08";
      eventDescription = "订单:" + orderID + "的调机单执行结果已经被验收，请相关岗位知悉！";
      messageContent = "生产订单" + orderID + "在机台:" + machineID + "上生产时发生质量异常，质量原因是:" + result + "调机结果已经被确认验收.请相关岗位知悉！";

      let bodysss = {
        eventDescription: eventDescription,
        eventDatetime: eventDatetime,
        eventTypeID: eventTypeID,
        eventID: eventID,
        messageContent: messageContent,
        msgContentTypeID: msgContentTypeID,
        factoryID: "TC00",
        pLineID: pLineID,
        machineID: machineID,
        pShiftID: pShiftID,
        teamID: teamID,
        pOrderID: pOrderID,
        productionBarcode: productionBarcode,
        materialBarcode: materialBarcode,
        relatedEmployee: relatedEmployee,
        messageStatus: messageStatus,
        processBatchID: processBatchID,
        beginDatetime: beginDatetime,
        sendFinished: sendFinished,
        closed: closed
      };
      try {
        let res = await _httpClient.post(
          _httpClient.getApiPrefix() + "/RealtimeEventMessage/SaveEntity",
          {
            body: bodysss,
          }
        );
        if (res.Message == null) {
          Toast.clear();
          //Toast.success("发送成功");
        } else {
          Toast.clear();
          //Toast.fail("发送失败");
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },
    //验证逻辑
    async startRepair(id, machineID, orderID, recycleTest, afterAdjustStatus, result) {
      try {
        let res = await _httpClient.get(
          _httpClient.getApiPrefix() +
          "/QualityAbnormalNotice/GetList?GetComfirmed=false&ResourceFrom=APP&MachineID=" + val + "",
        );
        if (res.Total === 1) {
          try {
            let res = await _httpClient.get(
              _httpClient.getApiPrefix() +
              "/QualityAbnormalNotice/GetList?GetComfirmed=false&ResourceFrom=LAB&MachineID=" + val + "",
            );
            if (res.Total >= 1) {
              Toast.clear();
              alert("存在实验室未验收调机单，不允许调机验收");
              return 1;
            } else {
              //保存数据
              this.startAdjust();
              //发送消息
              this.sendmessage(id, machineID, orderID, recycleTest, afterAdjustStatus, result);
              return 0;
            }
          } catch (e) {
            //Toast.fail(JSON.stringify(e));
          }
        } else {
          //保存数据
          this.startAdjust();
          //发送消息
          this.sendmessage(id, machineID, orderID, recycleTest, afterAdjustStatus, result);
          return 0;
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },
    async getUncheckedListPlus(a1, a2) {
      // alert(a1);
      // alert(a2);
      let _this = this;
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "Loading...",
      });
      try {
        let res = await _httpClient.get(
          _httpClient.getApiPrefix() +
          "/QualityAbnormalNotice/GetList?GetComfirmed=false&ResourceFrom=" + a2 + "&MachineID=" + a1 + "",
        );
        // alert( _httpClient.getApiPrefix() +
        //   "/QualityAbnormalNotice/GetList?GetComfirmed=false&ResourceFrom="+a1+"&MachineID="+a2+"");
        _this.itemsOne = [];
        //alert(JSON.stringify(res));
        if (res.Total === 0) {
          Toast.clear();
        } else {
          Toast.clear();
          _this.itemsOne = res.Data;
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },
    //查询未验收数据
    async getUncheckedList() {
      let _this = this;
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "Loading...",
      });
      try {
        let res = await _httpClient.get(
          _httpClient.getApiPrefix() +
          "/QualityAbnormalNotice/GetList?GetComfirmed=false&LogOnUserID="+_this.user.userId,
        );
        if (res.Total === 0) {
          Toast.clear();
        } else {
          Toast.clear();
          _this.itemsOne = res.Data;
          _this.itemsOne.forEach((item) => {
            let depart = { key: item.MachineID, value: item.MachineID }
            _this.columnsshift1.push(depart)
            _this.searchColumns.push(depart)
          });
          _this.columnsshift1 = Array.from(new Set(_this.columnsshift1.map(JSON.stringify))).map(JSON.parse);
          _this.searchColumns = Array.from(new Set(_this.searchColumns.map(JSON.stringify))).map(JSON.parse);
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },
    //查询已接受调机数据
    async getCheckedList() {
      let _this = this;
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "Loading...",
      });
      try {
        let res = await _httpClient.get(
          _httpClient.getApiPrefix() +
          "/QualityAbnormalNotice/GetList?GetComfirmed=true&LogOnUserID="+_this.user.userId,
        );
        if (res.Total === 0) {
          Toast.clear();
        } else {
          Toast.clear();
          _this.itemsTwo = res.Data;
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },
  },
};
</script>
<style>
body {
  background-color: White;
}

.formstyle {
  margin-top: 4px;
  font-size: 15px;
  font-weight: bold;
  display: flex;
  align-items: center;
}


.pic {
  width: 100%;
  text-align: center;
}

.divMedia {
  margin-top: 10px;
  height: 190px;
  border: solid #dcdcdc;
  margin-left: 5px;
  margin-right: 15px;
  border-top-width: 4px;
  border-left-width: 4px;
  border-right-width: 1px;
}

.clickbtn {
  width: 1;
  margin: 5px 10px;
  line-height: 45px;
  border: 1px #ccc dashed;
  text-align: center;
}

.buttonRight {
  position: fixed;
  margin-top: -40px;
  right: 15px;
  width: 90px;
  height: 40px;
  background-color: #1c6c8d;
  border-color: #1c6c8d;
}

.buttonLeft {
  position: fixed;
  margin-top: -40px;
  right: 110px;
  width: 90px;
  height: 40px;
  background-color: #1c6c8d;
  border-color: #1c6c8d;
}

.message {
  font-size: 20px;
  margin-top: 0px;
  margin-left: -10px;
  font-weight: bold;
}

.divStyle {
  /* border: 1px solid #dcdcdc; */
  border-top-width: 3px;
  border-left-width: 3px;
  margin-left: 3px;
  margin-right: 3px;
  margin-top: 0px;
}

.pagination {
  position: fixed;
  bottom: 15px;
  width: 100%;
  color: rgb(0, 0, 255);
  text-align: center;
}

.textScrol3 {
  display: inline-block;
  position: fixed;
  top: 17.2rem;
  bottom: 1px;
  overflow: scroll;
  right: 0;
  width: 100%;
  margin-bottom: 0.5rem;
  z-index: 1;
}

.textScroll {
  display: inline-block;
  position: fixed;
  top: 10.2rem;
  bottom: 1px;
  overflow: scroll;
  right: 0;
  width: 100%;
  margin-bottom: 0.5rem;
  z-index: 1;
}

.textScroll2 {
  display: inline-block;
  position: fixed;
  top: 10rem;
  left: 0;
  bottom: 1px;
  overflow-y: scroll;
  width: 100%;
  margin-bottom: 0.5rem;
  z-index: 1;
  overflow-x: hidden;
  /*解决ios上滑动不流畅*/
  -webkit-overflow-scrolling: touch;
}
</style>
